<?php

function getProjects($con, $db_name, $requestVars,$sessionEnabled, $type)
{
    $pid = $requestVars['pid'];

    
    $status =  $requestVars['status'];
    
    $requestVars =  CheckSessionAndPermissions($con, $db_name,$sessionEnabled, $requestVars, 'projects','get',$type);
   
    if($requestVars['s_uid'] != "{" && $type == 'json' || 
       $requestVars['s_uid'] != "<" && $type == 'xml')
    {     
        $uid = $requestVars['s_uid'];        
    }
    else
    {  
        return $requestVars; // Because this is really the invalid response...
    }
    
    
    
    $query = "SELECT p.* FROM $db_name.projekte p
             join $db_name.projekte_assigned pa on p.id = pa.projekt
            WHERE pa.user = $uid";
    
      
    // We want to get a specific Project.
    if($pid)
    {
        $query .= " and p.id= $pid";
    } 
    
    if($status != "" && ($status == 0 || $status==1))
    {
        $query = $query." and status = $status";
    }
     $result = mysqli_query($con,$query);

    if(!$result)
    {
        die("mysql error: ".mysql_error()."[$query]");
    }
    
    $ProjectArray = array();
    $counter = 0;
    
    while($row = mysqli_fetch_assoc($result))
    {
      $id = $row['ID'];
      
      if ($row["end"])
      {
        $daysleft = getDaysLeft($row["end"]);

        $endstring = date("d.m.Y", $row["end"]);
        $row["endstring"] = $endstring;
      }
      else 
      {
        $daysleft =" ";
      }

     $startDate = $row['start'];  
     $endDate = $row['end'];
     $projectName = $row['name'];

     $projectDesc = $row['desc'];
     $projectDone = getProgress($row['id']);
     
     $budget = $row['budget'];
     $statusrow = $row['status'];

     $Project =  new Project($id,$projectName, $projectDesc, $startDate, $endDate, $daysleft,$projectDone,$budget, $statusrow);

     $ProjectArray[$counter] = $Project;
     $counter++;
 
    
    }

    if($pid)
    {
        if($type == 'json')
        {
            return ProjectResponseJSON(1,"Success!",$id,$projectName, $projectDesc, $startDate, $endDate, $daysleft,$projectDone,$budget, $statusrow);
        }
        else if($type == 'xml')
        {
            return ProjectResponseXML(1,"Success!",$id,$projectName, $projectDesc, $startDate, $endDate, $daysleft,$projectDone,$budget, $statusrow);
        }        
    }
    else
    {
        if($type == 'json')
        {
            return ArrayProjectResponseJSON(1,"Success!",$ProjectArray);
        }
        else if($type == 'xml')
        {
            return ArrayProjectResponseXML(1,"Success!",$ProjectArray);
        }        
    }
}

function addProject($con, $db_name, $requestVars,$sessionEnabled, $type)
{
    $requestVars =  CheckSessionAndPermissions($con, $db_name,$sessionEnabled, $requestVars, 'projects','add',$type);
   
    if($requestVars['s_uid'] != "{" && $type == 'json' || 
       $requestVars['s_uid'] != "<" && $type == 'xml')
    {     
        $uid = $requestVars['s_uid'];        
    }
    else
    {  
        return $requestVars; // Because this is really the invalid response...
    }
    
    $name = $requestVars['name']; 
    $desc = $requestVars['desc'];
    $end =  $requestVars['end'];
    $budget = $requestVars['budget'];
    $assignme = $requestVars['assignme'];

    if(!$assignme)
    {
        $assignme = 0; 
    }

    $name = mysqli_real_escape_string($con,$name);
    $desc = mysqli_real_escape_string($con,$desc);
    $end = mysqli_real_escape_string($con,$end);
    $assignme = (int) $assignme;
    $budget = (float) $budget;

    if ($end > 0) {
        $end = strtotime($end);
    }
    $now = time();

    $query  = "INSERT INTO $db_name.projekte (`name`, `desc`, `end`, `start`, `status`, `budget`) VALUES ('$name','$desc','$end','$now',1,'$budget')";
    $result = mysqli_query($con,$query);

    if(!$result)
    {
        die("mysql error: ".mysql_error()."[$query]");
    }

    $pid = mysqli_insert_id($con);
    if ($assignme == 1) {
        // Assign this user to it. 
        $query  = "INSERT INTO $db_name.projekte_assigned (`user`, `projekt`) VALUES ('$uid','$pid')";
        $result = mysqli_query($con,$query);

        if(!$result)
        {
            die("mysql error: ".mysql_error()."[$query]");
        }                            

    }
    $query  = "SELECT * From $db_name.projekte WHERE id = $pid";
    $result = mysqli_query($con,$query);

    if(!$result)
    {
        die("mysql error: ".mysql_error()."[$query]");
    }

    while($row = mysqli_fetch_assoc($result))
    {
        $id = $row['ID'];
        $name = $row['name'];
        $desc = $row['desc'];
        $start = $row['start'];
        $end = $row['end'];
        $budget = $row['budget'];
        $status = $row['status'];
        $daysleft = getDaysLeft($row["end"]);
        $done = getProgress($row['id']);
    }

    if($type == 'json')
    {            
        return ProjectResponseJSON(1,"Success!",$id,$name,$desc,$start,$end,$daysleft, $done,$budget,$status);
    }
    else if($type == 'xml')
    {
        return ProjectResponseXML(1,"Success!",$id,$name,$desc,$start,$end,$daysleft, $done,$budget,$status);
    }                            

}

 
function editProject($con, $db_name, $requestVars,$sessionEnabled, $type)
{
    $pid = $requestVars['pid'];
    
    if(!$pid)
    {
        if($type == 'json')
        {
            return GenericResponseJSON(7, "You must pass a project id (pid) !");
        }
        else if($type == 'xml')
        {
            return GenericResponseXML(7, "You must pass a project id (pid) !");
        }        
    }
    
     $requestVars =  CheckSessionAndPermissions($con, $db_name,$sessionEnabled, $requestVars, 'projects','edit',$type);
   
    if($requestVars['s_uid'] != "{" && $type == 'json' || 
       $requestVars['s_uid'] != "<" && $type == 'xml')
    {     
        $uid = $requestVars['s_uid'];        
    }
    else
    {  
        return $requestVars; // Because this is really the invalid response...
    }
            
            
    $name = $requestVars['name'];
    $desc  = $requestVars['desc'];
    $end = $requestVars['end'];
    $budget = $requestVars['budget'];    

    $get ="select * from $db_name.projekte WHERE ID=$pid";
    $result =  mysqli_query($con,$get);

    if(!$result)
    {
        die("mysql error: ".mysql_error()."[$get]");
    }
    while($row = mysqli_fetch_assoc($result))
    {

        if(!$name)
        {

            $name = $row['name'];                    
        }
        else
        {
            $name = mysqli_real_escape_string($con,$name);
        }

        if(!$desc)
        {
            $desc = $row['name'];
        }
        else
        {
            $desc = mysqli_real_escape_string($con,$desc);
        }

        if(!$end)
        {
            $end =    $row['end'];

        }
        else
        {
            $end = mysqli_real_escape_string($con,$end);
            $end = strtotime($end);
        }
        if(!$budget)
        {
            $budget = $row['budget'];
        } 
        $start = $row['start'];
        $status = $row['status'];
        
        
    }         

    $daysleft = getDaysLeft($end);
    $done = getProgress($pid);
    $pid = mysqli_real_escape_string($con,$pid);            

    $budget = (float) $budget;
    $pid = (int) $pid;


    $upd = mysqli_query($con,"UPDATE $db_name.projekte SET name='$name',`desc`='$desc',`end`='$end',budget=$budget WHERE ID = $pid");

    if($upd) 
    {
        if($type == 'json')
        {            
            return ProjectResponseJSON(1,"Success!",$pid,$name,$desc,$start,$end,$daysleft, $done,$budget,$status);
        }
        else if($type == 'xml')
        {
            return ProjectResponseXML(1,"Success!",$pid,$name,$desc,$start,$end,$daysleft, $done,$budget,$status);
        }            
    } 
    else 
    {        
        if($type == 'json')
        {
            return GenericResponseJSON(14, "Failed to update project, please try again later");
        }
        else if($type == 'xml')
        {
            return GenericResponseXML(14, "Failed to update project, please try again later");
        }
         
    }         
    
}

function delProject($con, $db_name, $requestVars,$sessionEnabled,$type)
{
    $pid = $requestVars['pid'];
    
    if(!$pid)
    {
        if($type == 'json')
        {
            return GenericResponseJSON(7, "You must pass a project id (pid) !");
        }
        else if($type == 'xml')
        {
            return GenericResponseXML(7, "You must pass a project id (pid) !");
        }        
    }
    
    $requestVars =  CheckSessionAndPermissions($con, $db_name,$sessionEnabled, $requestVars, 'projects','del',$type);
   
    if($requestVars['s_uid'] != "{" && $type == 'json' || 
       $requestVars['s_uid'] != "<" && $type == 'xml')
    {     
        $uid = $requestVars['s_uid'];        
    }
    else
    {  
        return $requestVars; // Because this is really the invalid response...
    }
    
    $pid = mysqli_real_escape_string($con,$pid);

    $pid = (int) $pid;
    // Delete assignments of tasks of this project to users            
    $get ="select * from $db_name.tasks WHERE project=$pid";
    $result =  mysqli_query($con,$get);
    if(!$result)
    {
        die("mysql error: ".mysql_error()."[$get]");
    }
    while($row = mysqli_fetch_assoc($result))
    {

        $del_taskAssigned = mysqli_query($con,"DELETE FROM $db_name.tasks_assigned WHERE task = ".$row['ID']);
    }

    $del_messages = mysqli_query($con,"DELETE FROM $db_name.messages WHERE project = $pid");
    $del_milestones = mysqli_query($con,"DELETE FROM $db_name.milestones WHERE project = $pid");
    $del_projectassignments = mysqli_query($con,"DELETE FROM $db_name.projekte_assigned WHERE projekt = $pid");
    $del_tasklists = mysqli_query($con,"DELETE FROM $db_name.tasklist WHERE project = $pid");
    $del_tasks = mysqli_query($con,"DELETE FROM $db_name.tasks WHERE project = $pid");
    $del_timetracker = mysqli_query($con,"DELETE FROM $db_name.timetracker WHERE project = $pid");

    $del_logentries = mysqli_query($con,"DELETE FROM $db_name.log WHERE project = $pid");
    $del = mysqli_query($con,"DELETE FROM $db_name.projekte WHERE ID = $pid");

    if ($del) 
    {
        if($type == 'json')
        {
             return GenericResponseJSON(1, "Success!");
        }
        else if($type == 'xml')
        {
             return GenericResponseXML(1, "Success!");
        }       
    }
    else 
    {        
        if($type == 'json')
        {
            return GenericResponseJSON(18, "Failed to delete project, please try again later");
        }
        else if($type == 'xml')
        {
            return GenericResponseXML(18, "Failed to delete project, please try again later ");
        }
         
    }         
}

function closeProject($con, $db_name, $requestVars,$sessionEnabled, $type)
{
    $pid = $requestVars['pid'];
    
    if(!$pid)
    {
        if($type == 'json')
        {
            return GenericResponseJSON(7, "You must pass a project id (pid) !");
        }
        else if($type == 'xml')
        {
            return GenericResponseXML(7, "You must pass a project id (pid) !");
        }
        
    }
    
    $requestVars =  CheckSessionAndPermissions($con, $db_name,$sessionEnabled, $requestVars, 'projects','close',$type);
   
    if($requestVars['s_uid'] != "{" && $type == 'json' || 
       $requestVars['s_uid'] != "<" && $type == 'xml')
    {     
        $uid = $requestVars['s_uid'];        
    }
    else
    {  
        return $requestVars; // Because this is really the invalid response...
    }
    $pid = mysqli_real_escape_string($con,$pid);
    $pid = (int) $pid;           


    $selMilestones = mysqli_query($con,"Select * FROM $db_name.milestones WHERE project = $pid");
    if(!$selMilestones)
    {
          die("mysql error: ".mysql_error()."Select * FROM $db_name.milestones WHERE project = $pid");
    }            
    while($row = mysqli_fetch_assoc($selMilestones))
    {
         $close_milestones = mysqli_query($con,"UPDATE $db_name.milestones SET status = 0 WHERE ID = ".$row['ID']);              
    }

    $selTasks= mysqli_query($con,"Select * FROM $db_name.tasks WHERE project = $pid");
    if(!$selTasks)
    {
          die("mysql error: ".mysql_error()."Select * FROM $db_name.tasks WHERE project = $pid");
    }

    while($row = mysqli_fetch_assoc($selTasks))
    {
         $close_tasks = mysqli_query($con,"UPDATE $db_name.tasks SET status = 0 WHERE ID = ".$row['ID']);              
    }

    $selTasklists = mysqli_query($con,"Select * FROM $db_name.tasklist WHERE project = $pid");
    if(!$selTasklists)
    {
          die("mysql error: ".mysql_error()."Select * FROM $db_name.tasklist WHERE project = $pid");
    }

    while($row = mysqli_fetch_assoc($selTasklists))
    {
         $close_tasklists = mysqli_query($db_name,"UPDATE $db_name.tasklist SET status = 0 WHERE ID = ".$row['ID']);              
    }



    $upd = mysqli_query($con,"UPDATE $db_name.projekte SET status=0 WHERE ID = $pid");
    if ($upd) 
    {
        if($type == 'json')
        {
             return GenericResponseJSON(1, "Success!");
        }
        else if($type == 'xml')
        {
             return GenericResponseXML(1, "Success!");
        }       
    }
    else 
    {        
        if($type == 'json')
        {
            return GenericResponseJSON(21, "Failed to close project, please try again later");
        }
        else if($type == 'xml')
        {
            return GenericResponseXML(21, "Failed to close project, please try again later");
        }
         
    }      
}
function openProject($con, $db_name, $requestVars,$sessionEnabled, $type)
{
    $pid = $requestVars['pid'];
    
    if(!$pid)
    {
        if($type == 'json')
        {
            return GenericResponseJSON(7, "You must pass a project id (pid) !");
        }
        else if($type == 'xml')
        {
            return GenericResponseXML(7, "You must pass a project id (pid) !");
        }
        
    }
    
    $requestVars =  CheckSessionAndPermissions($con, $db_name,$sessionEnabled, $requestVars, 'projects','close',$type);
   
    if($requestVars['s_uid'] != "{" && $type == 'json' || 
       $requestVars['s_uid'] != "<" && $type == 'xml')
    {     
        $uid = $requestVars['s_uid'];        
    }
    else
    {  
        return $requestVars; // Because this is really the invalid response...
    }
            
    $pid = mysqli_real_escape_string($con,$pid);
    $pid = (int) $pid;

    $upd = mysqli_query($con,"UPDATE $db_name.projekte SET status=1 WHERE ID = $pid");
    if ($upd) 
    {
        if($type == 'json')
        {
             return GenericResponseJSON(1, "Success!");
        }
        else if($type == 'xml')
        {
             return GenericResponseXML(1, "Success!");
        }       
    }
    else 
    {        
        if($type == 'json')
        {
            return GenericResponseJSON(26, "Failed to open project, please try again later");
        }
        else if($type == 'xml')
        {
            return GenericResponseXML(26, "Failed to open project, please try again later");
        }
         
    }         
     
}

function AddUserToProject($con, $db_name, $requestVars,$sessionEnabled, $type)
{
    $pid = $requestVars['pid'];
    
    if(!$pid)
    {
        if($type == 'json')
        {
            return GenericResponseJSON(7, "You must pass a project id (pid) !");
        }
        else if($type == 'xml')
        {
            return GenericResponseXML(7, "You must pass a project id (pid) !");
        }
        
    }
    
    $requestVars =  CheckSessionAndPermissions($con, $db_name,$sessionEnabled, $requestVars, 'projects','addUser',$type);
   
    if($requestVars['s_uid'] != "{" && $type == 'json' || 
       $requestVars['s_uid'] != "<" && $type == 'xml')
    {     
        $uid = $requestVars['s_uid'];        
    }
    else
    {  
        return $requestVars; // Because this is really the invalid response...
    }
    
    // Override adding yourself auto-magically by passing uid. 
    $uid = $requestVars['uid'];
    
    $uid = mysqli_real_escape_string($con,$uid);
    $pid = mysqli_real_escape_string($con,$pid);
    $uid = (int) $uid;
    $pid = (int) $pid;

    $ins = mysqli_query($con,"INSERT INTO $db_name.projekte_assigned (user,projekt) VALUES ($uid,$pid)");
    if ($ins)
    {
        if($type == 'json')
        {
             return GenericResponseJSON(1, "Success!");
        }
        else if($type == 'xml')
        {
             return GenericResponseXML(1, "Success!");
        } 
    }
    else
    {
        if($type == 'json')
        {
            return GenericResponseJSON(34, "Failed to add user to project, please try again later");
        }
        else if($type == 'xml')
        {
            return GenericResponseXML(34, "Failed to add user to project, please try again later");
        }
    }
}

?>
